import React, { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Upload,
  Switch,
  Row,
  Col,
  message,
  Space,
  Card,
  Tag,
  Divider
} from 'antd';
import {
  UploadOutlined,
  SaveOutlined,
  CloseOutlined,
  EyeOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import { DocumentApi, DocumentVO, DocumentCategoryVO } from '../../../api/document';

const { Option } = Select;
const { TextArea } = Input;

interface DocumentFormProps {
  document?: DocumentVO | null;
  categories: DocumentCategoryVO[];
  onSave: () => void;
  onCancel: () => void;
}

const DocumentForm: React.FC<DocumentFormProps> = ({
  document,
  categories,
  onSave,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);

  // 状态选项
  const statusOptions = [
    { label: '草稿', value: 0 },
    { label: '已发布', value: 1 },
    { label: '已下线', value: 2 },
  ];

  useEffect(() => {
    if (document) {
      form.setFieldsValue({
        title: document.title,
        categoryId: document.categoryId,
        content: document.content,
        summary: document.summary,
        tags: document.tags,
        status: document.status,
        isTop: document.isTop,
        allowComment: (document as any).allowComment,
        author: document.author,
      });

      // 设置附件列表
      if ((document as any).attachments) {
        setFileList(
          (document as any).attachments.map((file: any, index: number) => ({
            uid: index.toString(),
            name: file.name,
            status: 'done',
            url: file.url,
          }))
        );
      }
    } else {
      form.resetFields();
      setFileList([]);
    }
  }, [document, form]);

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const formData = {
        ...values,
        attachments: fileList.map(file => ({
          name: file.name,
          url: file.url || file.response?.url,
        })),
      };

      if (document) {
        await DocumentApi.updateDocument(formData);
        message.success('更新成功');
      } else {
        await DocumentApi.createDocument(formData);
        message.success('创建成功');
      }

      onSave();
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 文件上传处理
  const handleUploadChange = ({ fileList: newFileList }: any) => {
    setFileList(newFileList);
  };

  // 预览内容
  const handlePreview = () => {
    const content = form.getFieldValue('content');
    if (!content) {
      message.warning('请先输入内容');
      return;
    }
    setPreviewVisible(true);
  };

  // 自动生成摘要
  const handleGenerateSummary = () => {
    const content = form.getFieldValue('content');
    if (!content) {
      message.warning('请先输入内容');
      return;
    }
    
    // 简单的摘要生成逻辑：取前200个字符
    const summary = content.replace(/<[^>]*>/g, '').substring(0, 200) + '...';
    form.setFieldValue('summary', summary);
    message.success('摘要已自动生成');
  };

  return (
    <div>
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          status: 0,
          isTop: false,
          allowComment: true,
        }}
      >
        <Row gutter={16}>
          <Col span={16}>
            <Form.Item
              name="title"
              label="文档标题"
              rules={[{ required: true, message: '请输入文档标题' }]}
            >
              <Input placeholder="请输入文档标题" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="categoryId"
              label="文档分类"
              rules={[{ required: true, message: '请选择文档分类' }]}
            >
              <Select placeholder="请选择分类">
                {categories.map(category => (
                  <Option key={category.id} value={category.id}>
                    {category.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="content"
          label={
            <Space>
              <span>文档内容</span>
              <Button
                type="link"
                size="small"
                icon={<EyeOutlined />}
                onClick={handlePreview}
              >
                预览
              </Button>
            </Space>
          }
          rules={[{ required: true, message: '请输入文档内容' }]}
        >
          <TextArea
            rows={12}
            placeholder="请输入文档内容，支持Markdown格式"
          />
        </Form.Item>

        <Form.Item
          name="summary"
          label={
            <Space>
              <span>文档摘要</span>
              <Button
                type="link"
                size="small"
                onClick={handleGenerateSummary}
              >
                自动生成
              </Button>
            </Space>
          }
        >
          <TextArea
            rows={3}
            placeholder="请输入文档摘要，用于搜索和展示"
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item name="tags" label="标签">
              <Select
                mode="tags"
                placeholder="请输入标签，按回车添加"
                tokenSeparators={[',']}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="author" label="作者">
              <Input placeholder="请输入作者" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item name="attachments" label="附件">
          <Upload
            fileList={fileList}
            onChange={handleUploadChange}
            beforeUpload={() => false} // 阻止自动上传
            multiple
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>

        <Divider />

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item name="status" label="发布状态">
              <Select>
                {statusOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="isTop" label="是否置顶" valuePropName="checked">
              <Switch />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="allowComment" label="允许评论" valuePropName="checked">
              <Switch />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item>
          <Space>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              loading={loading}
              onClick={handleSubmit}
            >
              保存
            </Button>
            <Button icon={<CloseOutlined />} onClick={onCancel}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 内容预览模态框 */}
      {previewVisible && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0,0,0,0.5)',
            zIndex: 1000,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
          onClick={() => setPreviewVisible(false)}
        >
          <Card
            title="内容预览"
            style={{ width: '80%', maxHeight: '80%', overflow: 'auto' }}
            extra={
              <Button
                type="text"
                icon={<CloseOutlined />}
                onClick={() => setPreviewVisible(false)}
              />
            }
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                whiteSpace: 'pre-wrap',
                lineHeight: '1.6',
                fontSize: '14px',
              }}
            >
              {form.getFieldValue('content')}
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

export default DocumentForm;